import React,{useState,useEffect} from 'react'
import { Table,Button,Modal,Tree } from 'antd';
import { DeleteOutlined,UnorderedListOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
const { confirm } = Modal;
export default function RoleList() {
  const [dataSource, setdataSource] = useState([])
  const [rightList, setrightList] = useState([])
  const [currentRight, setcurrentRight] = useState([])
  const [currentId, setcurrentId] = useState(0)
  const [isModalVisible, setisModalVisible] = useState(false)
  useEffect(() => {
    axios.get('/roles').then(res=>{
      setdataSource(res.data)
    })
    axios.get('/rights?_embed=children').then(res=>{
      setrightList(res.data)
    })
  
    return () => {
      
    }
  }, [])
  
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render:(id)=>{
        return <b>{id}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName'
    },
    {
      title: '操作',
      render:(item)=>{
        return(
          <div>
            <Button danger type="primary" shape="circle" icon={<DeleteOutlined />} onClick={()=>{
              confirmMethod(item)
            }} />
            <Button type="primary" shape="circle" icon={<UnorderedListOutlined />} onClick={()=>{
              setisModalVisible(true)
              setcurrentId(item.id)
              setcurrentRight(item.rights)
            }} />
          </div>
        )
      }
    },
  ];
  const confirmMethod = (item)=>{
    confirm({
      title: '你确定要删除吗',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      onOk() {
        deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const deleteMethod = (item)=>{
    setdataSource(dataSource.filter(data=>data.id !== item.id))
    axios.delete(`/roles/${item.id}`)
  }
  const handleOk = ()=>{
    setisModalVisible(false)
    // 同步datascource
    setdataSource(dataSource.map(item=>{
      if(item.id === currentId){
        return {
          ...item,
          rights:currentRight
        }
      }
      return item
    }))
    axios.patch(`/roles/${currentId}`,{
      rights:currentRight
    })
  }
  const handleCancel = ()=>{
    setisModalVisible(false)
  }
  const onCheck = (checkeKeys)=>{
    setcurrentRight(checkeKeys.checked)
  }
  return (
    <div>
      <Table dataSource={dataSource} columns={columns} rowKey={(item)=>item.id} />
      <Modal title="权限分配" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Tree
          checkable
          checkedKeys={currentRight}
          onCheck={onCheck}
          checkStrictly
          treeData={rightList}
        />
      </Modal>   
    </div>
  )
}
